package main

import (
	"context"
	"errors"
	"fmt"
	"{{.ProjectName}}/config"
	initplugs "{{.ProjectName}}/init_plugs"
	"{{.ProjectName}}/middles"
	"{{.ProjectName}}/routers"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	// 读取配置
	config.ReadConfig("./config/config.yaml")
	cfg := config.Cfg
	// 插件初始化
	initplugs.InitPlugs()
	// 创建服务
	var router *gin.Engine
	switch cfg.Env {
	case "pro":
		// 生产模式
		gin.SetMode(gin.ReleaseMode)
		router = gin.New()
	case "dev":
		// 调试模式
		gin.SetMode(gin.DebugMode)
		router = gin.New()
	default:
		panic(errors.New("env配置错误,只支持:pro生产模式,dev调试模式"))
	}
	// 增加中间件
	middles.AddMiddleWare(router)
	// 路由初始化
	routers.InitRouters(router)
	// 启动服务
	srv := &http.Server{
		Addr:    fmt.Sprintf("%s:%v", cfg.Ip, cfg.Port),
		Handler: router,
	}
	go func() {
		// 监听服务
		initplugs.LogSuger.Info(fmt.Sprintf("服务启动: %s:%v", cfg.Ip, cfg.Port))
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %v\n", err)
		}
	}()
	// 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
	<-quit
	initplugs.LogSuger.Info("Shutdown Server ...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatalf("Server Shutdown:%v", err)
	}
	initplugs.LogSuger.Info("Server exiting")
}
